package com.shigu.component.shiro.filter;

import com.shigu.mo.enums.SessionEnum;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * 登陆的用户过滤器
 */
public abstract class UserLoginFilter implements Filter {

    @Value("${main_host}")
    private String MAIN_HOST;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    /**
     * 登陆判断
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public boolean hasLogin(String loginUrl,HttpServletRequest request,HttpServletResponse response) throws IOException {
        Session session = SecurityUtils.getSubject().getSession();
        Object auth=session.getAttribute(SessionEnum.LOGIN_USER.toString());
        if(auth==null) {
            redirectToUrl(loginUrl,request,response);
            return false;
        }else{
            return true;
        }
    }
    /**
     * 重组链接回调给一个地址
     * @param reurl
     * @param request
     * @param response
     * @throws IOException
     */
    public void redirectToUrl(String reurl, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String url=request.getRequestURL().toString();
        if(url.endsWith(".json")||url.endsWith(".action")){
            String jsonString = JSONObject.fromObject("{'result':'error','msg':'请先登陆'}").toString();
            response.setCharacterEncoding("UTF-8");
            if (request.getParameter("callback") != null) {
                response.setContentType("application/x-javascript");//jsonp异常响应处理
                jsonString = request.getParameter("callback") + "(" + jsonString + ");";
            } else {
                response.setContentType("application/json");//修复post异常信息未被解析为json
            }
            writeToResponse(response,jsonString);
        }else{
            String queryString=request.getQueryString();
            String backUrl=URLEncoder.encode(url+
                    (queryString==null?"":("?"+queryString)), "utf-8").replace("%","!");
             response.sendRedirect(MAIN_HOST+"toWxBind.htm?type=2&backUrl="+URLEncoder.encode(reurl + "/" + backUrl,"UTF-8"));
        }
    }

    public void writeToResponse(HttpServletResponse response,String jsonString){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");//修复post异常信息未被解析为json
        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.print(jsonString);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
